package com.usernet.product.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.usernet.product.entity.Admin;
import com.usernet.product.tools.AdminRight;
import com.usernet.product.utils.LogConstants;
import com.usernet.product.utils.ProductConfig;
import com.usernet.product.utils.ProductUtils;

public class AdminFilter implements Filter {

	public void init(FilterConfig fc) throws ServletException {
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		Admin admin = (Admin) session.getAttribute("admin");

		if (admin == null
				&& !request.getRequestURI().equals("/admin/login.jsp")
				&& !request.getRequestURI().equals("/admin/index.jsp")) {
			response.setCharacterEncoding(ProductConfig.CHARSET);
			PrintWriter out = response.getWriter();
			out.write("<div align=center>AdminRefuseAccess</div>");
			out.flush();
			out.close();
		} else if (request.getServletPath().toLowerCase().indexOf("delete") > 0// 删除
				|| request.getServletPath().toLowerCase().indexOf("ok") > 0) {// 解锁
			if (admin.getStatus() != AdminRight.supers) {
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(),
						LogConstants.not_agreen, null);
				response.setCharacterEncoding(ProductConfig.CHARSET);
				PrintWriter out = response.getWriter();

				out.write("<div align=center>您没有权限</div>");
				out.flush();
				out.close();
			} else {
				chain.doFilter(req, res);
			}
		} else {
			chain.doFilter(req, res);
		}

	}

	public void destroy() {
	}
}